﻿using System;
using System.IO;
using SevenZip.Compression.LZMA;

namespace LZMA
{
    public sealed class Extractor
    {
        private static byte[] GetLzmaProperties(Stream inStream, out long outSize)
        {
            byte[] LZMAproperties = new byte[5];
            if (inStream.Read(LZMAproperties, 0, 5) != 5)
            {
                throw new Exception();
            }
            outSize = 0;
            for (int i = 0; i < 8; i++)
            {
                int b = inStream.ReadByte();
                if (b < 0)
                {
                    throw new Exception();
                }
                outSize |= ((long)(byte)b) << (i << 3);
            }
            return LZMAproperties;
        }

        /// <summary>
        /// Decompress byte array compressed with LZMA algorithm (C# inside)
        /// </summary>
        /// <param name="data">Byte array to decompress</param>
        /// <returns>Decompressed byte array</returns>
        public static byte[] ExtractBytes(byte[] data)
        {
            using (MemoryStream inStream = new MemoryStream(data))
            {
                Decoder decoder = new Decoder();
                inStream.Seek(0, 0);
                using (MemoryStream outStream = new MemoryStream())
                {
                    long outSize;
                    decoder.SetDecoderProperties(GetLzmaProperties(inStream, out outSize));
                    decoder.Code(inStream, outStream, inStream.Length - inStream.Position, outSize, null);
                    return outStream.ToArray();
                }
            }
        }
    }
}
